<?php
class Comment
{
    public static function addComment()
    {

        $name = Request::post('name');
        $email = Request::post('email');
        $comment = Request::post('comment');
        $img = Request::post('img');
        $postId = Request::post('id');
        // 对数据进行验证
        if (empty($email) || empty($comment) || empty($img) || empty($postId)) {
            return false;
        }
        // 是否符合邮箱格式
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return false;
        }
        // HTML转义
        $name = htmlspecialchars($name);
        $email = htmlspecialchars($email);
        $comment = htmlspecialchars($comment);
        $img = htmlspecialchars($img);
        $postId = htmlspecialchars($postId);

        // 获取浏览器指纹
        $BrowserFingerprint = Authentication::getBrowserFingerprint();
        // 检查是否存在该评论
        $comments = Sql::init('comments')->where(array('postID' => $postId, 'BrowserFingerprint' => $BrowserFingerprint))->query();
        if (!empty($comments)) {
            // 检查在多条记录中是否存在该评论
            foreach ($comments as $commentItem) {
                if ($commentItem['comment'] == $comment) {
                    return HttpData::result('json', 403, "您已经评论过了", false);
                }
            }
            // 检查是否在2分钟内评论过
            if (time() - $comments[count($comments)-1]['created_at'] < 120) {
                return HttpData::result('json', 403, "您评论过于频繁，请两分钟后再试", false);
            }
        }

        // 添加评论
        $result = Sql::init('comments')->setData(array('name' => $name, 'email' => $email, 'comment' => $comment, 'img' => $img, 'postID' => $postId, 'created_at' => time(), 'updated_at' => time(), 'ip' => $_SERVER['REMOTE_ADDR'], 'BrowserFingerprint' => $BrowserFingerprint))->insert();
        if (!$result) {
            return HttpData::result('json', 200, "success", true);
        } else {
            return HttpData::result('json', 403, "error", false);
        }
    }
    public static function good() {
        $postId = Request::param('id');
        // 验证数据
        if (empty($postId)) {
            return false;
        }
        // 获取浏览器指纹
        $BrowserFingerprint = Authentication::getBrowserFingerprint();

        // 检查是否存在该点赞记录
        $likes = Sql::init('likes')->where(array('postID' => $postId, 'BrowserFingerprint' => $BrowserFingerprint))->query();
        if (!empty($likes)) {
            // 检查在多条记录中是否存在该点赞记录
            if(!empty($likes)){
                return HttpData::result('json', 403, "您已经点赞过了", false);
            }
        }
        // 添加点赞记录
        $result = Sql::init('likes')->setData(array('postID' => $postId, 'created_at' => time(), 'ip' => $_SERVER['REMOTE_ADDR'], 'BrowserFingerprint' => $BrowserFingerprint))->insert();
        if (!$result) {
            return HttpData::result('json', 200, "success", true);
        } else {
            return HttpData::result('json', 403, "error", false);
        }
    

    }
}
